<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="shell是一个命令行解释器，它接收应用程序&#x2F;用户命令，然后调用操作系统内核。编写shell程序管理集群，提升开发效率。 创建一个shell脚本123456789101112# 在&#x2F;home&#x2F;jsgo002&#x2F;Documents&#x2F;linux 目录下创建一个hwd.txt文件，并写入“This an example.”touch exp.shchmod +x exp.shvi exp.sh#i#!&#x2F;b">
<meta property="og:type" content="article">
<meta property="og:title" content="shell">
<meta property="og:url" content="https://bgape002.gitee.io/2021/09/05/shell/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="shell是一个命令行解释器，它接收应用程序&#x2F;用户命令，然后调用操作系统内核。编写shell程序管理集群，提升开发效率。 创建一个shell脚本123456789101112# 在&#x2F;home&#x2F;jsgo002&#x2F;Documents&#x2F;linux 目录下创建一个hwd.txt文件，并写入“This an example.”touch exp.shchmod +x exp.shvi exp.sh#i#!&#x2F;b">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-05T11:59:09.000Z">
<meta property="article:modified_time" content="2021-09-06T07:17:01.549Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="shell">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bgape002.gitee.io/2021/09/05/shell/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>shell | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2021/09/05/shell/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          shell
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-09-05 19:59:09" itemprop="dateCreated datePublished" datetime="2021-09-05T19:59:09+08:00">2021-09-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-09-06 15:17:01" itemprop="dateModified" datetime="2021-09-06T15:17:01+08:00">2021-09-06</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/linux/" itemprop="url" rel="index"><span itemprop="name">linux</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2021/09/05/shell/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2021/09/05/shell/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><strong>shell是一个命令行解释器，它接收应用程序/用户命令，然后调用操作系统内核。</strong>编写shell程序管理集群，提升开发效率。</p>
<h3 id="创建一个shell脚本"><a href="#创建一个shell脚本" class="headerlink" title="创建一个shell脚本"></a>创建一个shell脚本</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在/home/jsgo002/Documents/linux 目录下创建一个hwd.txt文件，并写入“This an example.”</span></span><br><span class="line"><span class="built_in">touch</span> exp.sh</span><br><span class="line"><span class="built_in">chmod</span> +x exp.sh</span><br><span class="line">vi exp.sh</span><br><span class="line"><span class="comment">#i</span></span><br><span class="line"><span class="comment">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> /home/jsgo002/Documents/linux</span><br><span class="line"><span class="built_in">touch</span> hwd.txt </span><br><span class="line"><span class="built_in">echo</span> <span class="string">&quot;This a example.&quot;</span> &gt;&gt; hwd.txt</span><br><span class="line"><span class="comment">#:wq</span></span><br><span class="line">./exp.sh</span><br></pre></td></tr></table></figure>

<span id="more"></span>

<h3 id="定义变量"><a href="#定义变量" class="headerlink" title="定义变量"></a>定义变量</h3><ul>
<li><p>系统变量：<code>$HOME,$PWD,$USER</code>等</p>
</li>
<li><p>用户自定义变量：<code>A=2 \\ echo $A</code>;<code>unset A</code>撤销变量。</p>
</li>
<li><p>静态变量：<code>readonly B=3</code>.注意，静态变量不能做<code>unset</code>处理。</p>
</li>
<li><p><code>export 变量名</code>：将变量提升为全局变量。（可在shell文本中全局调用）</p>
</li>
<li><p><code>$n</code>：n为数字，<code>$n代表该脚本名称，$1-$9代表第1到9个参数，10以上的参数需要用大括号包括，$&#123;10&#125;</code>。这个类似于python的format。</p>
<p>例：<code>./hwd.sh world of zhangsan</code>，则hwd.sh文本中<code>$0,$1,$2,$3</code>分别代表<code>hwd.sh,world,of,zhangsan</code></p>
</li>
<li><p><code>$#</code>：获取所有输入参数个数</p>
</li>
<li><p><code>$*</code>：代表命令行中所有的参数，它把所有的参数看成了一个整体</p>
</li>
<li><p><code>$@</code>：代表命令行中所有的参数，不过它把每个参数区分对待</p>
</li>
<li><p><code>$?</code>：最后一次执行命令的返回状态。0，表示上一个命令执行正确；非0，则表示上一个命令执行不正确</p>
</li>
<li><p>关于变量定义的注意事项：</p>
<blockquote>
<ol>
<li>变量名称可以由字母、数字和下划线组成，但不能以数字开头。环境变量名建议大写。</li>
<li>等号两侧不能有空格。</li>
<li>在bash中，变量默认类型都是字符串类型，无法直接进行数值运算。</li>
<li>变量的值如果由空格，需要用双引号或单引号括起来。</li>
</ol>
</blockquote>
</li>
</ul>
<h3 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h3><ul>
<li><p><code>$((运算式))</code>或<code>$[运算式]</code></p>
</li>
<li><p><code>expr +,-,\*,/,&amp;</code><strong>注意乘号，expr运算符间要有空格</strong></p>
<p>一步计算(2+3)X4：<code>expr</code> <code>`</code> <code>expr 2 + 3</code> <code>`</code> <code>\* 4</code></p>
</li>
</ul>
<h3 id="条件判断"><a href="#条件判断" class="headerlink" title="条件判断"></a>条件判断</h3><ul>
<li><p>[ condition ] </p>
<blockquote>
<p>注意：</p>
<ul>
<li>condition前后要有空格</li>
<li>条件非空即为true，[]为false</li>
</ul>
</blockquote>
</li>
<li><p>两个整数之间的比较</p>
<blockquote>
<ul>
<li>= 字符串比较</li>
<li>-eq 等于(equal)</li>
<li>-lt 小于(less than)</li>
<li>-le 小于等于(less equal)</li>
<li>-gt 大于(greater than)</li>
<li>-ge 大于等于(greater equal)</li>
<li>-ne 不等于(not equal)</li>
</ul>
</blockquote>
</li>
<li><p>按照文件权限进行判断</p>
<blockquote>
<p>-r 有读的权限</p>
<p>-w 有写的权限</p>
<p>-x 有执行的权限</p>
</blockquote>
</li>
<li><p>按照文件类型进行判断</p>
<blockquote>
<p>-f 文件存在并且是一个常规文件</p>
<p>-e 文件存在</p>
<p>-d 文件存在并且是一个目录</p>
</blockquote>
</li>
<li><p>例： <code>[ 23 -ge 22 ] \\ echo $?</code> 23是否大于等于22</p>
</li>
<li><p>hwd.sh 是否有写权限：<code>[ -w hwd.sh ] \\ echo $?</code></p>
</li>
<li><p>hwd.sh 是否为目录文件： <code>[ -d hwd.sh ] \\ echo $?</code></p>
</li>
<li><p>多条件判断，&amp;&amp;逻辑与，||逻辑或：<code>[ condition ] &amp;&amp; echo OK || echo NotOK</code></p>
</li>
</ul>
<h3 id="流程控制"><a href="#流程控制" class="headerlink" title="流程控制"></a>流程控制</h3><ul>
<li><p>if 判断</p>
<blockquote>
<p><strong>基本语法</strong></p>
<p>if [ 条件判断式 ];then </p>
<p>​    程序</p>
<p>fi</p>
<hr>
<p>if  [ 条件判断式 ]</p>
<p>​    then</p>
<p>​        程序</p>
<p>fi</p>
<p><strong>注意：</strong></p>
<ul>
<li>[  ]前后必须有空格</li>
<li>if 后要有空格</li>
</ul>
<p><strong>例：</strong>输入一个数字，如果是1返回true，如果是2返回yes,否则返回false</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$1</span> -eq 1 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">	<span class="built_in">echo</span> <span class="string">&quot;true&quot;</span></span><br><span class="line"><span class="keyword">elif</span> [<span class="variable">$1</span> -eq 2]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">	<span class="built_in">echo</span> <span class="string">&quot;yes&quot;</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">	<span class="built_in">echo</span> <span class="string">&quot;false&quot;</span></span><br><span class="line"><span class="keyword">fi</span>	</span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>case语句</p>
<blockquote>
<p><strong>基本语法</strong></p>
<p>case $变量名 in</p>
<p>“a”）</p>
<p>如果变量值等于a，则执行程序1</p>
<p>;;</p>
<p>“b”)</p>
<p>如果变量值等于b，则执行程序2</p>
<p>;;</p>
<p>……</p>
<p>*)</p>
<p>如果变量值都不是以上值，则执行此程序</p>
<p>;;</p>
<p>esac</p>
<p><strong>注意：</strong></p>
<ul>
<li>case行尾必须尾单词<code>in</code>，每一个模式匹配必须以<code>)</code>结束</li>
<li>双分好<code>;;</code>表示命令序列结束，类似<code>break</code></li>
<li>最后的<code>*)</code>·表示默认模式，类似<code>default</code></li>
</ul>
</blockquote>
</li>
<li><p>for循环</p>
<blockquote>
<p><strong>基本语法</strong></p>
<p>for((初始值；循环控制条件；变量变化))</p>
<p>do</p>
<p>​    程序</p>
<p>done</p>
<hr>
<p><strong>例：</strong>计算1-100累加和</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">s=0</span><br><span class="line"><span class="keyword">for</span>((i=1;i&lt;=100;i++))</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">	s=$[<span class="variable">$s</span>+<span class="variable">$i</span>]</span><br><span class="line"><span class="keyword">done</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$s</span></span><br></pre></td></tr></table></figure>

<p><strong>基本语法2</strong></p>
<p>for 变量 in 值1 值2 值3…</p>
<p>do</p>
<p>​    程序</p>
<p>done</p>
<p><strong>例：</strong>打印所有输入参数</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> $*</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">	<span class="built_in">echo</span> <span class="variable">$i</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>while循环</p>
<blockquote>
<p><strong>基本语法</strong></p>
<p>while [ condition ]</p>
<p>do</p>
<p>​    program</p>
<p>done</p>
</blockquote>
</li>
</ul>
<h3 id="read-读取控制台输入"><a href="#read-读取控制台输入" class="headerlink" title="read 读取控制台输入"></a>read 读取控制台输入</h3><ul>
<li><p>基本语法</p>
<blockquote>
<p>read(opt)(param)</p>
<p>opt:</p>
<ul>
<li>-p指定读取值时的提示符</li>
<li>-t指定读取值时等待的时间（s）</li>
</ul>
<p>param:</p>
<ul>
<li>变量：指定读取值的变量名</li>
</ul>
</blockquote>
</li>
<li><p>例：提示7s内，读取控制台输入的名称</p>
<blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">read</span> -t 7 -p <span class="string">&quot;Enter your name in 7s&quot;</span> NAME</span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$NANE</span></span><br></pre></td></tr></table></figure></blockquote>
</li>
</ul>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><ul>
<li><p>系统函数</p>
<blockquote>
<ul>
<li>basename [string/pathname] [suffix] 删除所有前面包括最后一个（’/‘）字符，然后将字符串显示出来。suffix为后缀，如果suffix被指定了，basename会将pathname/string中的suffix去掉。</li>
<li>例：<code>basename /home/jsgo002/exam.txt </code> –&gt; exam.txt // <code>basename /home/jsgo002/exam.txt .txt</code> –&gt; exam</li>
</ul>
<hr>
<ul>
<li>dirname 文件绝对路径  // 从给定的包含绝对路径的文件名中删除文件名，然后返回剩下的路径（目录部分）</li>
<li>例：<code>dirname /home/jsgo002/exam.txt</code> –&gt; /home/jsgo002</li>
</ul>
</blockquote>
</li>
<li><p>自定义函数</p>
<blockquote>
<p><strong>基本语法</strong></p>
<p>[ function ] funcname[()]</p>
<p>{</p>
<p>​    Action;</p>
<p>​    [return int;]</p>
<p>}</p>
<hr>
<p><strong>备注</strong></p>
<ul>
<li>必须在调用函数地方之前，先声明函数。shell脚本是逐行运行的，不会像其他语言一样先编译。</li>
<li>函数返回值，只能通过$?系统变量获得，可以显示return返回，若不加return，则以最后一条命令结果作为返回值。</li>
</ul>
<p><strong>例：</strong>计算两个输入参数的和</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="function"><span class="title">sum</span></span>()</span><br><span class="line">&#123;</span><br><span class="line">	s=0;</span><br><span class="line">	s=$[ <span class="variable">$1</span> + <span class="variable">$2</span> ];</span><br><span class="line">	<span class="built_in">echo</span> <span class="string">&quot;<span class="variable">$s</span>&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">read</span> -p “input a number <span class="keyword">for</span> n1” n1;</span><br><span class="line"><span class="built_in">read</span> -p <span class="string">&quot;input a number for n2&quot;</span> n2;</span><br><span class="line"><span class="built_in">sum</span> <span class="variable">$n1</span> <span class="variable">$n2</span>;</span><br></pre></td></tr></table></figure></blockquote>
</li>
</ul>
<h3 id="shell工具"><a href="#shell工具" class="headerlink" title="shell工具"></a>shell工具</h3><ul>
<li><p>cut</p>
<blockquote>
<p><strong>功能</strong></p>
<p>从文件中剪切数据；从文件的每一行剪切字节、字符和字段并将其输出。</p>
<hr>
<p><strong>基本用法</strong></p>
<p>cut [opt] filename</p>
<p>注：默认分隔符是制表符</p>
<p><strong>参数说明</strong></p>
<ul>
<li>-f 列号，提取第几列</li>
<li>-d 分隔号，按指定分隔号分割列</li>
</ul>
<p><strong>例：</strong>获取系统PATH变量值，第2个“：”后的所有路径</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$PATH</span> | <span class="built_in">cut</span> -d : -f 3-</span><br><span class="line"><span class="comment"># 3- 表示第3列以后所有列；3表示仅第3列；-3表示第3列后所有列（不含第3列）</span></span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>sed</p>
<blockquote>
<p><strong>功能</strong></p>
<p>sed是一种流编辑器，它一次处理一行内容。处理时，把当前处理的行储存在临时缓冲区中，称为“模式空间”，接着用sed命令处理缓冲区中的内容，处理完成后，把缓冲区的内容送往屏幕。接着处理下一行，这样不断重复，直到文件末尾。</p>
<p>不改变源文件。</p>
<p><strong>基本用法</strong></p>
<p>sed [opt] ‘command’ filename</p>
<p><strong>opt</strong></p>
<ul>
<li>-e 直接在指令模式上进行sed的动作编辑</li>
</ul>
<p><strong>command</strong></p>
<ul>
<li>a 新增，a后面可以接字符串，在下一行出现</li>
<li>d 删除</li>
<li>s 查找并替换</li>
</ul>
<hr>
<p><strong>例：</strong>将we插入sed.txt的第二行；删除文件包含wo的行；将文件中wo替换成ni;将文件中的第二行删除并将wo替换成你</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1</span></span><br><span class="line">sed <span class="string">&quot;2a we&quot;</span> sed.txt</span><br><span class="line"><span class="comment"># 2</span></span><br><span class="line">sed <span class="string">&quot;/wo/d&quot;</span> sed.txt</span><br><span class="line"><span class="comment"># 3</span></span><br><span class="line">sed <span class="string">&quot;s/wo/ni/g&quot;</span> sed.txt</span><br><span class="line"><span class="comment"># 4</span></span><br><span class="line">sed -e <span class="string">&quot;2d&quot;</span> -e <span class="string">&quot;s/wo/ni/g&quot;</span> sed.txt</span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>awk</p>
<blockquote>
<p><strong>功能</strong></p>
<p>文本分析工具。把文件逐行读入，以空格为默认分隔符将每行切片，切开的部分再进行分析处理。</p>
<p><strong>基本用法</strong></p>
<p>awk [opt] ‘pattern1{action1} pattern2{action2}…’ filename</p>
<p><strong>pattern：</strong>表示awk在数据中查找的内容，即匹配模式（正则）</p>
<p><strong>action：</strong>在找到匹配内容是所执行的一系列命令</p>
<p><strong>opt</strong></p>
<ul>
<li>-F 指定输入文件的分隔符</li>
<li>-v 赋值一个用户定义变量</li>
</ul>
<hr>
<p><strong>例：</strong>搜索passwd文件以root关键字开头的所有行，并输出第7列</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">awk -F : <span class="string">&#x27;/^root/&#123;print $7&#125;&#x27;</span> passwd/bin/bash</span><br></pre></td></tr></table></figure></blockquote>
</li>
<li><p>sort</p>
<blockquote>
<p><strong>功能</strong></p>
<p>将文件进行排序，并将排序结果标准输出。</p>
<p><strong>基本语法</strong></p>
<p>sort(opt)(param)</p>
<p><strong>opt</strong></p>
<ul>
<li>-n 按数值大小排序</li>
<li>-r 以相反的顺序排序</li>
<li>-t 设置排序时的分隔符</li>
<li>-k 指定需要排序的列</li>
</ul>
<p><strong>param：</strong>指定待排序的文件列表</p>
<hr>
<p><strong>例：</strong>按文件中第2列数值大小倒序排列sdt.txt</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数据文本sdt.txt内容如下：</span></span><br><span class="line"><span class="comment"># ad:44:6:21</span></span><br><span class="line"><span class="comment"># dw:20:22:7</span></span><br><span class="line"><span class="comment"># we:34:21:19</span></span><br><span class="line"><span class="comment"># ee:12:23:11</span></span><br><span class="line"><span class="built_in">sort</span> -t : -nrt 2</span><br></pre></td></tr></table></figure></blockquote>
</li>
</ul>
<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1hW41167NW?from=search&seid=4711465121211906230&spm_id_from=333.337.0.0">尚硅谷Shell教程(shell自动化编程精讲)</a></p>
<p></font>&gt;</p>

    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/shell/" rel="tag"><i class="fa fa-tag"></i> shell</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/09/05/C++/" rel="prev" title="C++">
      <i class="fa fa-chevron-left"></i> C++
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2021/09/09/mysql-review/" rel="next" title="mysql review">
      mysql review <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AAshell%E8%84%9A%E6%9C%AC"><span class="nav-number">1.</span> <span class="nav-text">创建一个shell脚本</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F"><span class="nav-number">2.</span> <span class="nav-text">定义变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="nav-number">3.</span> <span class="nav-text">运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9D%A1%E4%BB%B6%E5%88%A4%E6%96%AD"><span class="nav-number">4.</span> <span class="nav-text">条件判断</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6"><span class="nav-number">5.</span> <span class="nav-text">流程控制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#read-%E8%AF%BB%E5%8F%96%E6%8E%A7%E5%88%B6%E5%8F%B0%E8%BE%93%E5%85%A5"><span class="nav-number">6.</span> <span class="nav-text">read 读取控制台输入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0"><span class="nav-number">7.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#shell%E5%B7%A5%E5%85%B7"><span class="nav-number">8.</span> <span class="nav-text">shell工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">9.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
